package cn.css0209.applicationdemo190509.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import cn.css0209.applicationdemo190509.MenuActivity;
import cn.css0209.applicationdemo190509.User.MainActivity;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static android.content.Context.MODE_PRIVATE;

public class OkHttp {
    private String result, is, sessionId;
    private Activity activity;

    public OkHttp(Activity activity) {
        this.activity = activity;
        sessionId = sessionID();
    }

    private String sessionID() {
        //        获取sessionID，确认登录状态
        SharedPreferences sharedPreferences = activity.getSharedPreferences("user", MODE_PRIVATE);
        String sessionId = sharedPreferences.getString("session", "");
        return sessionId;
    }


    //登录请求
    public void login(final String user, final String pwd) {
        new Thread(new Runnable() {//开启线程
            @Override
            public void run() {
                FormBody body = new FormBody.Builder()
                        .add("user", user)   //提交参账号和密码
                        .add("pwd", pwd)
                        .build();
                Request request = new Request.Builder()
                        .url("https://project.css0209.cn/api/user/login")  //请求的地址
                        .post(body)
                        .build();
                System.out.println("发送请求");
                OkHttpClient client = new OkHttpClient();

                try {
                    Response response = client.newCall(request).execute();
                    if (response.body() != null) {
                        System.out.println("接受请求");
                        result = response.body().string();           //获得值
                        System.out.println("处理请求");
                        JSONObject jx = JX(result);
                        JSONObject item = jx.getJSONObject("item");
                        if (jx.getString("result").equals("success")) {
                            is = "登陆成功！" + jx.getJSONObject("item").getString("username");
                            Headers headers = response.headers();
                            List cookies = headers.values("Set-Cookie");
                            String session = cookies.get(0).toString();
                            String sessionId = session.substring(0, session.indexOf(";"));//获取sessionId
                            SharedPreferences sharedPreferences = activity.getSharedPreferences("user", MODE_PRIVATE);
                            SharedPreferences.Editor editor = sharedPreferences.edit();
                            editor.putString("session", sessionId);
                            editor.putString("userNum", item.getString("userNum"));
                            editor.putString("userName", item.getString("username"));
                            editor.putString("Permission", item.getString("permission"));
                            editor.putString("Phone", item.getString("phone"));
                            editor.putString("Sex", item.getString("sex"));
                            editor.putString("Location", item.getString("location"));
                            editor.putString("specificAddress", item.getString("specificAddress"));
                            editor.apply();
                            Intent it = new Intent(activity, MenuActivity.class);
                            activity.startActivity(it);
                            activity.finish();
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    is = "网络异常";
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //    注册用户请求
    public void addUser(final String userNum, final String userName, final String pwd) {
        new Thread(new Runnable() {//开启线程
            @Override
            public void run() {
                FormBody body = new FormBody.Builder()
                        .add("usernum", userNum)   //提交账号和密码
                        .add("Username", userName)
                        .add("Password", pwd)
                        .add("Permission", "user")
                        .build();
                Request request = new Request.Builder()
                        .url("https://project.css0209.cn/api/user/add")  //请求的地址
                        .post(body)
                        .build();
                OkHttpClient client = new OkHttpClient();

                try {
                    Response response = client.newCall(request).execute();
                    if (response.body() != null) {
                        result = response.body().string();           //获得值
                        JSONObject jx = JX(result);
                        if (jx.getString("result").equals("success")) {
                            is = "注册成功！";
                            Intent it = new Intent(activity, MainActivity.class);
                            activity.startActivity(it);
                            activity.finish();
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    is = "error" + e;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void infoUser() {
        new Thread(new Runnable() {//开启线程
            @Override
            public void run() {
                FormBody body = new FormBody.Builder()
                        .build();
                Request request = new Request.Builder()
                        .url("https://project.css0209.cn/api/user/userInfo")  //请求的地址
                        .addHeader("cookie", sessionId)
                        .post(body)
                        .build();
                OkHttpClient client = new OkHttpClient();
                try {
                    Response response = client.newCall(request).execute();
                    if (response.body() != null) {
                        result = response.body().string();           //获得值
                        JSONObject jx = JX(result);
                        JSONObject item = jx.getJSONObject("item");
                        SharedPreferences preferences = activity.getSharedPreferences("user", MODE_PRIVATE);
                        SharedPreferences.Editor editor = preferences.edit();
                        editor.putString("userNum", item.getString("userNum"));
                        editor.putString("userName", item.getString("username"));
                        editor.putString("Permission", item.getString("permission"));
                        editor.putString("Phone", item.getString("phone"));
                        editor.putString("Sex", item.getString("sex"));
                        editor.putString("Location", item.getString("location"));
                        editor.putString("specificAddress", item.getString("specificAddress"));
                        editor.apply();
                        if (!jx.getString("result").equals("success")) {
                            is = "网络连接异常";
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    is = e.toString();
                    Intent it = new Intent(activity, MainActivity.class);
                    activity.startActivity(it);
                    activity.finish();
                }
            }
        }).start();
    }

    public void update(final JSONObject jsonObject) {
        new Thread(new Runnable() {//开启线程
            @Override
            public void run() {
                MediaType JSON = MediaType.parse("application/json; charset=utf-8");
                RequestBody body = RequestBody.create(JSON, String.valueOf(jsonObject));
                Request request = new Request.Builder()
                        .url("https://project.css0209.cn/api/user/update")  //请求的地址
                        .addHeader("cookie", sessionId)
                        .post(body)
                        .build();
                OkHttpClient client = new OkHttpClient();
                try {
                    Response response = client.newCall(request).execute();
                    if (response.body() != null) {
                        result = response.body().string();           //获得值
                        JSONObject jx = JX(result);
                        JSONObject item = jx.getJSONObject("item");
                        SharedPreferences preferences = activity.getSharedPreferences("user", MODE_PRIVATE);
                        SharedPreferences.Editor editor = preferences.edit();
                        editor.putString("userName", item.getString("username"));
                        editor.putString("Sex",item.getString("sex"));
                        editor.apply();
                        if (jx.getString("result").equals("success")) {
                            is = "修改成功";
                            Intent intent = new Intent(activity, MenuActivity.class);
                            activity.startActivity(intent);
                            activity.finish();
                        } else {
                            is = "网络连接异常";
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Intent it = new Intent(activity, MainActivity.class);
                    activity.startActivity(it);
                    activity.finish();
                }
            }
        }).start();
    }


    //    解析json
    private JSONObject JX(String date) {
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(date);
            String result = jsonObject.getString("result");//获取返回值result的内容
            if (!result.equals("success")) {
                is = jsonObject.getString("msg");
            }
            Message message = new Message();
            message.what = 1;
            handler.sendMessage(message);
        } catch (JSONException e) {
            is = "error" + e;
            e.printStackTrace();
        }
        return jsonObject;
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                if (is == null) {
                    System.out.println("is is null");
                } else if (is.isEmpty()) {
                    Toast.makeText(activity, is, Toast.LENGTH_LONG).show();
                }
            }
        }
    };
}
